package com.example.writting.ui.templates

import android.text.SpannableString
import android.text.Spanned
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.example.writting.R
import com.example.writting.databinding.ItemTemplateBinding

class TemplatesAdapter : RecyclerView.Adapter<TemplatesAdapter.ViewHolder>() {

    private var items = listOf<String>()
    private val difficultWords = mapOf(
        "换挡" to "容易和\"档\"混淆"
    )

    fun updateItems(newItems: List<String>) {
        items = newItems
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding = ItemTemplateBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(items[position])
    }

    override fun getItemCount() = items.size

    inner class ViewHolder(private val binding: ItemTemplateBinding) : RecyclerView.ViewHolder(binding.root) {
        fun bind(template: String) {
            val spannableString = SpannableString(template)
            
            // 标记易错字并添加点击事件
            for ((word, hint) in difficultWords) {
                var startIndex = 0
                while (true) {
                    val index = template.indexOf(word, startIndex)
                    if (index == -1) break
                    
                    // 添加红色样式
                    spannableString.setSpan(
                        ForegroundColorSpan(ContextCompat.getColor(binding.root.context, R.color.red_500)),
                        index,
                        index + word.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    
                    // 添加点击事件
                    spannableString.setSpan(
                        object : ClickableSpan() {
                            override fun onClick(view: View) {
                                Toast.makeText(binding.root.context, hint, Toast.LENGTH_SHORT).show()
                            }
                        },
                        index,
                        index + word.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    
                    startIndex = index + word.length
                }
            }
            
            binding.templateText.text = spannableString
            binding.templateText.movementMethod = android.text.method.LinkMovementMethod.getInstance()
        }
    }
} 